package com.tan.kotlintest.glide

import android.content.Context
import android.content.res.Resources
import android.graphics.*
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation

/*
 * Copyright (C) 2018 重庆一聊高科技有限公司
 * 版权所有
 *
 * 功能描述：glide加载圆角图片
 * 作者：txj
 * 创建时间：2018/6/28
 *
 * 修改人：
 * 修改描述：
 * 修改日期
 */
class GlideRoundTransform @JvmOverloads constructor(context: Context?, dp: Int = 4) : BitmapTransformation(context) {

    init {
        mRadius = Resources.getSystem().displayMetrics.density * dp
    }

    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap? {
        return roundCrop(pool, toTransform)
    }

    override fun getId(): String {
        return javaClass.name + Math.round(mRadius)
    }

    companion object {

        private var mRadius = 0f

        private fun roundCrop(pool: BitmapPool, source: Bitmap?): Bitmap? {
            if (source == null) return null

            var result: Bitmap? = pool.get(source.width, source.height, Bitmap.Config.ARGB_8888)
            if (result == null) {
                result = Bitmap.createBitmap(source.width, source.height, Bitmap.Config.ARGB_8888)
            }

            val canvas = Canvas(result!!)
            val paint = Paint()
            paint.shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
            paint.isAntiAlias = true
            val rectF = RectF(0f, 0f, source.width.toFloat(), source.height.toFloat())
            canvas.drawRoundRect(rectF, mRadius, mRadius, paint)
            return result
        }
    }
}